package com.hzw.saas.web.app.group.controller;


import java.util.ArrayList;
import java.util.Objects;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzw.saas.api.group.IGroupMemberReviewService;
import com.hzw.saas.api.group.IGroupMemberService;
import com.hzw.saas.api.group.IGroupService;
import com.hzw.saas.api.group.bo.GroupBo;
import com.hzw.saas.api.group.bo.GroupLogBo;
import com.hzw.saas.api.group.enums.GroupMemberStatus;
import com.hzw.saas.api.group.query.GroupQuery;
import com.hzw.saas.api.group.query.GroupUQuery;
import com.hzw.saas.api.user.IUserProfileService;
import com.hzw.saas.api.user.bo.UserProfileBO;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.config.util.PageParam;
import com.hzw.saas.common.security.utils.SecurityUtils;
import com.hzw.saas.web.app.group.annotation.GroupOperation;
import com.hzw.saas.web.app.group.dto.SearchGroupDto;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;

/**
 * <p>
 * 用户组表 前端控制器
 * </p>
 *
 * @author sonam
 * @since 2020-12-23
 */
@RestController
@AllArgsConstructor
@Slf4j
@Api(tags = "群组管理/群组信息")
public class GroupController {

    private final IGroupService groupService;
    private final IUserProfileService userProfileService;
    private final IGroupMemberService groupMemberService;
    private final IGroupMemberReviewService groupMemberReviewService;
    private final MapperFacade mapperFacade;

    @GetMapping("/group/{groupId}")
    @ApiOperationSort(1)
    @ApiOperation(value = "获取群组信息", notes = "获取群组信息")
    @ApiImplicitParam(name = "groupId", value = "群组id", required = true, paramType = "path")
    public ResponseEntity<GroupBo> doesExist(@PathVariable String groupId) {
        // 判断当前用户是否在这个群组里面
        return ResponseEntity.ok(groupService.getGroupById(groupId));
    }

    @SysLog(operation = "创建群组")
    @PostMapping("/group")
    @ApiOperation(value = "创建群组", notes = "创建群组")
    @ApiResponses({
            @ApiResponse(code = 200, message = "创建的群组信息", response = GroupBo.class)
    })
    @ApiOperationSort(2)
    public ResponseEntity<GroupBo> submitGroup(@Valid @RequestBody GroupQuery group) {
        /**
         *  1、判断当前用户的群组名称是否重复
         *  2、判断父群组是否有效
         *  3、添加群组
         *  4、设置创建用户为管理员
         */
        GroupBo groupDto = groupService.submitGroup(group, getUserId());
        return ResponseEntity.ok(groupDto);
    }

    @SysLog(operation = "删除群组")
    @GroupOperation(groupId = "#groupId", errorMsg = "无权限删除群组")
    @DeleteMapping("/group/{groupId}")
    @ApiOperation(value = "删除群组", notes = "指定群组id删除群组")
    @ApiImplicitParam(name = "groupId", value = "删除的群组ID（以后可能是个数组）", required = true)
    @ApiResponses({
            @ApiResponse(code = 200, message = "true, 删除成功;false，删除失败")
    })
    @ApiOperationSort(3)
    public ResponseEntity<Boolean> delGroup(@PathVariable String groupId) {
        return ResponseEntity.ok(groupService.delGroup(groupId));
    }

    @SysLog(operation = "修改群组信息")
    @GroupOperation(groupId = "#group.groupId", errorMsg = "无权限修改群组")
    @PutMapping("/group")
    @ApiOperation(value = "修改群组信息", notes = "修改群组信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "true")
    })
    @ApiOperationSort(4)
    public ResponseEntity<Boolean> updateGroup(@Valid @RequestBody GroupUQuery group) {
        /**
         * 1、判断当前群组，是否属于当前用户，是则可以修改，不是则不能修改
         * 2、TODO 通过角色判断是否可以修改
         */
        return ResponseEntity.ok(groupService.updateGroup(group, getUserId()));
    }

    @GetMapping("/group/activities/{groupId}")
    @ApiOperation(value = "获取群组动态", notes = "查询群组动态")
    @ApiOperationSort(5)
    public ResponseEntity<IPage<GroupLogBo>> getGroupDynamic(@PathVariable String groupId, PageParam page) {
        return ResponseEntity.ok(groupService.getGroupDynamicById(page.convert(), groupId));
    }

    private String getUserId() {
        return SecurityUtils.getUser().getUserId();
    }

    @GetMapping("/group/search")
    @ApiOperation(value = "查询群组", notes = "通过群组名称模糊分页查询没有加入的群组信息")
    @ApiOperationSort(6)
    public ResponseEntity<IPage<SearchGroupDto>> searchGroupInfo(PageParam pageParam, @ApiParam(name = "groupName", value = "群组名称（群组名称）") @RequestParam("groupName")String groupName) {
        String userId = getUserId();
        IPage<GroupBo> groupBoPage = groupService.searchGroupByUserAndGroupName(pageParam, userId, groupName);
        IPage<SearchGroupDto> searchGroupDtoIPage = new Page<>(groupBoPage.getCurrent(), groupBoPage.getSize(), groupBoPage.getTotal(), groupBoPage.isSearchCount());
        searchGroupDtoIPage.setRecords(new ArrayList<>());
        groupBoPage.getRecords().forEach(groupBo -> {
            SearchGroupDto searchGroupDto = mapperFacade.map(groupBo, SearchGroupDto.class);
            UserProfileBO userProfileBO = userProfileService.get(groupBo.getOwnerId());
            if(Objects.isNull(userProfileBO)) {
                searchGroupDto.setOwnerName("null");
            } else {
                searchGroupDto.setOwnerName(userProfileBO.getRealName());
            }
            searchGroupDto.setGroupUserNum(groupMemberService.getMemberCountByGroupId(groupBo.getGroupId()));
            GroupMemberStatus groupMemberStatus = groupMemberReviewService.getGroupMemberStatus(userId, groupBo.getGroupId(), 0);
            searchGroupDto.setApplyStatus(groupMemberStatus.value());
            searchGroupDto.setApplyText(groupMemberStatus.text());
            searchGroupDtoIPage.getRecords().add(searchGroupDto);
        });
        return ResponseEntity.ok(searchGroupDtoIPage);
    }

}
